<template>
  <div class="searchRecords">
    <van-search
      v-model="inputVal"
      show-action
      :placeholder="computedPlaceholder"
      @search="handleSearch"
      @cancel="onCancel"
      @clear="clearInputVal"
      autofocus
      @input="handleInputSearch">
      <template #left>
        <div class="van-search__action" @click="onCancel">取消</div>
      </template>
      <template #action>
        <div @click="handleSearch">搜索</div>
      </template>
    </van-search>
    <div class="jobArr" v-if="isShow && (keyWord === 'hasWorkedList' || keyWord === 'lendMoney')">
      <com-job-item
        v-for="(item, index) in needObj"
        :key="index"
        :id="item.id"
        :keyWord="keyWord"
        :jobItem="item"
        :path="$route.path"
      ></com-job-item>
    </div>

    <div class="jobArr" v-if="isShow && keyWord === 'wageSettlement'">
      <com-job-item
        v-for="(item, index) in jobList"
        :key="index"
        :id="item"
        :keyWord="'wageSettlement'"
        :jobItem="item"
        :typeenrool="1"
        :searchNameType="searchNameType"
        :titleName="titleName"
        :searchVal="inputVal"
        :serchType="1"
      >
      </com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'recommendPersons'"
      class="recommend_list"
      style="box-sizing: border-box; text-align: center; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-recommend-item v-for="(item, index) in recommendList" :item="item" :key="index"></com-recommend-item>
    </div>

    <div
      v-if="isShow && keyWord === 'ratingList'"
      class="recommend_list"
      style="box-sizing: border-box; text-align: center; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-rate-item :rateRspObj="rateRspObj"></com-rate-item>
    </div>

    <div
      v-if="isShow && keyWord === 'recruitStaff'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :searchNameType="searchNameType"
        :titleName="titleName"
        :keyWord="'recruitmentManagement'"
        :searchVal="inputVal"
        :searchType="1"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'upstreamDownstreamManagement'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'upstreamDownstreamManagement'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'hasSignUpList'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'hasSignUpList'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'collectionHistory'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'collectionHistory'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'browsingHistory'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-job-item
        :jobItem="item"
        :typeenrool="1"
        :keyWord="'browsingHistory'"
        v-for="(item, index) in needObj"
        :key="index"
        @saveBrowsingHistoryList="toSaveBrowsingHistoryList"
      ></com-job-item>
    </div>

    <div
      v-if="isShow && keyWord === 'myAttention'"
      class="recommend_list"
      style="box-sizing: border-box; background-color: #FFFFFF; border-top: 1px solid #eee"
    >
      <com-my-attention v-for="(item, index) in needObj" :data-item="item" :key="index"></com-my-attention>
    </div>

    <!-- 分页  -->
    <div class="bottomPage" style>
      <van-pagination v-if="totalRecord"
        v-model="searchParams.pageIndex"
        :total-items="totalRecord"
        :items-per-page="searchParams.pageSize"
        force-ellipses
        @change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import {recordTypeObj_search} from '../../constants/comUtils'
import comJobItem from '../../components/comJobItem'
import comRecommendItem from '../../components/comRecommendItem'
import comMyAttention from '../../components/comMyAttention'
import comRateItem from '../myCompany/companyHome/common/comRateItem'
import {obj} from '../../constants/comUtils'
import {formatDate} from '@/utils/format'

export default {
  name: 'searchRecords',
  components: {
    comJobItem,
    comRecommendItem,
    comMyAttention,
    comRateItem
  },
  data() {
    return {
      needObj: {
        photos: [],
        educations: [],
        certificate_type: []
      },
      inputVal: '',
      recordTypeObj_search,
      keyWord: '',
      isShow: false,
      recommendList: [],
      rateRspObj: {
        rateArr: [
          {
            title: '对用人企业的评价',
            score: -3,
            desc: '考试中每道题的分值相等、枫叶将故事染色 结局我看透'
          },
          {
            title: '对招聘企业的评价',
            score: 4,
            desc: '花开就一次成熟 我却错过、枫叶将故事染色 结局我看透'
          },
          {
            title: '对近聘平台的评价',
            score: 5,
            desc: '谁在用琵琶弹奏、一曲东风破岁月在墙上剥落 看见小时候而如今琴声幽幽 我的等候你没听过'
          }
        ],
        time: '2021-02-22 15:35:17'
      },
      dataName: '',
      searchNameType: null,
      titleName: null,
      searchParams: {
        keyword: '', // 搜索关键字
        lng: null, // 经度
        lat: null, // 维度
        cityId: '', // 城市ID
        streetId: '', // 街道ID
        jobcategory: '', // 招聘类型
        orderItem: '', // 排序字段
        minSalary: null, // 起始薪资
        maxSalary: null, // 最大薪资
        nearby: '', // 附近地址
        classproperties: '', // 班制属性
        jobattributes: '', // 职位属性
        benefits: '', // 福利列表
        paymode: '', // 算薪方式
        payday: '', // 发薪日
        payMoneyDetailDate: '', // 发薪日详细日期
        createTime: '', // 发布时间
        pageIndex: 1, // 当前页
        pageSize: 10, // 每页显示条数
        selectId: ''
      }, // 检索参数

      jobList: [],
      totalRecord: 0
    }
  },
  created() {
    if (this.$route.params.id) {
      this.keyWord = this.$route.params.id
      this.dataName = this.$route.params.id
    } else {
      this.$router.back()
    }
    if (this.keyWord === 'recruitStaff') {
      this.searchNameType = this.$route.query.id
      this.titleName = this.$route.query.titleName
    }
  },
  computed: {
    computedPlaceholder() {
      switch (this.keyWord) {
        case 'wageSettlement':
          return '请输入工资结算的关键词'
        case 'recommendPersons':
          return `搜索手机号，用户昵称`
        case 'username':
          return '请输入姓名搜索'
        case 'xycompany':
          return '请输入公司搜索'
        case 'upstreamDownstreamManagement':
          return '请输入招聘信息、公司名称搜索'
        case 'getApplyCost':
          return '请输入招聘信息、公司名称、姓名搜索'
        case 'companyAndName':
          return '请输入公司名称、姓名搜索'
        case 'workInfo':
          return '请输入招聘信息、姓名搜索'
        case 'myAttention':
          return '请输入我关注的搜索'
        default:
          return `请输入${this.recordTypeObj_search[this.keyWord]}搜索`
      }
    }
  },
  methods: {
    // 公共函数
    async _getJobList() {
      const res = await this.$api.job.getJobPage(this.searchParams)
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    async _getJobCollectList() {
      const res = await this.$api.job.reqJobCollectList(this.searchParams)
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    async _getBrowsingHistory() {
      const res = await this.$api.job.reqBrowsingHistory(this.searchParams)
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    toSaveBrowsingHistoryList(val) {
      // 仅用于点击首页的工作，点击保存记录
      // 若没有找到了, 则结果为undefined
      if (val) {
        val.recordTime = new Date()
      }
      this.saveBrowsingHistoryList.unshift(val)
      localStorage.setItem('saveBrowsingHistory', JSON.stringify(this.saveBrowsingHistoryList))
    },
    onSearch(val) {
      console.log('点击回车', val)
      let that = this
      that.searchParams.keyword = val
      that._getJobList()
      that.isShow = true
    },
    async handleInputSearch(val) {
      let that = this
      if (val) {
        console.log('不断输入', val)
        that.searchParams.keyword = val
        that.handleSearch()
      }
    },
    async handleSearch(pageIndex) {
      let that = this
      that.isShow = true
      that.totalRecord = 0
      let page = parseInt(pageIndex)
      that.searchParams.pageIndex = isNaN(page) ? 1 : page

      console.log(this.dataName)
      if (that.dataName === 'collectionHistory') {
        that._getJobCollectList()
      } else if (that.dataName === 'browsingHistory') {
        that._getBrowsingHistory()
      } else if (that.dataName === 'myAttention') {
        that._getMyAttention()
      } else if (that.dataName === 'recruitStaff') {
        that._getJobList1()
      } else if (that.dataName === 'workInfo') {
        that.getJobInfo()
      } else if (that.dataName === 'wageSettlement') {
        that.getWageSettlementJobs()
      } else if (that.dataName === 'hasWorkedList') {
        that.getJobBeenWorking()
      } else if (that.dataName === 'recommendPersons') {
        that.reqMyRecommendPersons()
      } else {
        that._getJobList()
      }
      this.isShow = true
    },
    async getJobBeenWorking() {
      let userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const res = await this.$api.job.getJobBeenWorking({
        ...this.searchParams,
        UserId: userInfo.id
      })
      if (res.code === 200) {
        this.needObj = res.data.jobs
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    async _getJobList1() {
      let res = {}
      if (this.$route.query.type === 'workInfo') {
        res = await this.$api.job.getJobInfo(this.searchParams)
      } else {
        res = await this.$api.job.getMycompanyJobPage(this.searchParams)
      }
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },
    async _getMyAttention() {
      const res = await this.$api.job.getFollowList(this.searchParams)
      if (res.code === 200) {
        this.needObj = res.data.items
        this.total = res.data.count
        if (this.total == 0) this.totalType = 0
      }
    },

    async reqMyRecommendPersons() {
      const params = {
        pageIndex: this.searchParams.pageIndex,
        pageSize: this.searchParams.pageSize,
        key: this.searchParams.keyword
      }
      const res = await this.$api.others.reqMyRecommendPersons(params);
      if (res.code === 200){
        this.recommendList = res.data.items;
        this.totalRecord = res.data.count;
      };
    },

    onCancel() {
      this.$router.back()
    },

    clearInputVal() {
      this.isShow = false
    },

    toJobDetailPage(id) {
      console.log('已工作---子到父---进入详情', id)
      this.$router.push({
        path: `/jobDetail/${id}`
      })
    },

    //获取工资结算对应的工作信息
    async getWageSettlementJobs() {
      let param = {
        keyword: this.searchParams.keyword
      }

      const result = await this.$api.job.GetWageSettlementJobs(param)
      if (result.code == 200) {
        let jobList = []
        for (let item of result.data.settlementJobInfoList) {
          let jobItem = {
            rowid: item.ids,
            id: item.id,
            ids: item.ids,
            enterprise_name: item.jobName,
            recruiting_position: item.recruitingPosition,
            min_comprehensive_salary: item.minComprehensiveSalary ? parseInt(item.minComprehensiveSalary) : 0,
            max_comprehensive_salary: item.maxComprehensiveSalary ? parseInt(item.maxComprehensiveSalary) : 0,
            payway_id: item.payWayId,
            job_category_id: item.jobCategoryId,
            create_time: formatDate(item.signUpTime, '-', ':'),
            status: item.status ? parseInt(item.status) : item.status,
            work_address_fulle_address: item.workAddressFulleAddress,
            fulle_address: item.fulleAddress,
            interview_address_fulle_address: item.interviewAddressFulleAddress,
            generation_instructions: item.generationInstructions,
            generation_of_commission: item.generationOfCommission,
            fee_unit: item.feeUnit,
            isLendMoney: 1,
            work_start_time: formatDate(item.startDate, '-', ':'),
            work_end_time: formatDate(item.overDate, '-', ':'),
            apply_time: formatDate(item.signUpTime, '-', ':'),
            first_value_input: item.firstValueInput,
            salaryuptime: formatDate(item.salaryTime, '-', ':'),
            salarymoney: item.salaryMoney,
            salaryInfoId: item.salaryInfoId,
            switch_state: item.switchState,
            job_status: item.jobStatus
          }

          jobList.push(jobItem)
        }

        this.jobList = jobList
      }
    },

    handlePageChange(value) {
      this.handleSearch(value)
    }
  }
}
</script>

<style lang="scss" scoped>
.searchRecords {
  width: 100%;
  .recommend_list {
    padding-bottom: 1.1px;
    box-sizing: border-box;
    background-color: #ffffff;
    font-size: 12px;
  }
}
</style>
